<?php
namespace app\api\model;

use think\Model;

class DictData extends Model
{
    // 设置表名
    protected $table = 'system_dict_data';

    // 设置主键
    protected $pk = 'dict_code';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    // 字段类型转换
    protected $type = [
        'dict_code'  => 'integer',
        'dict_sort'  => 'integer',
        'status'     => 'integer',
    ];

    /**
     * 获取字典数据列表
     * @param array $params 查询参数
     * @return array
     */
    public function getList($params = [])
    {
        $page = isset($params['pageNum']) ? intval($params['pageNum']) : 1;
        $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 10;

        $query = $this->order('dict_type', 'asc')
            ->order('create_time', 'desc');

        // 字典类型搜索
        if (!empty($params['dictType'])) {
            $query->where('dict_type', $params['dictType']);
        }

        // 字典标签搜索
        if (!empty($params['dictLabel'])) {
            $query->whereLike('dict_label', "%{$params['dictLabel']}%");
        }

        // 状态搜索
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('status', $params['status']);
        }

        $total = $query->count();
        $list = $query->page($page, $pageSize)->select();

        return [
            'rows'  => $list,
            'total' => $total
        ];
    }

    /**
     * 根据字典类型获取字典数据
     * @param string $dictType 字典类型
     * @return array
     */
    public function getByDictType($dictType)
    {
        return $this->where('dict_type', $dictType)
            ->where('status', 0)
            ->order('dict_sort', 'asc')
            ->select();
    }

    /**
     * 检查字典标签是否唯一
     * @param string $dictType 字典类型
     * @param string $dictLabel 字典标签
     * @param int $excludeCode 排除的编码
     * @return bool
     */
    public function checkDictLabelUnique($dictType, $dictLabel, $excludeCode = null)
    {
        $query = $this->where('dict_type', $dictType)
            ->where('dict_label', $dictLabel);

        if ($excludeCode) {
            $query->where('dict_code', '<>', $excludeCode);
        }

        return $query->count() === 0;
    }

    /**
     * 根据字典类型删除数据
     * @param string $dictType 字典类型
     * @return int
     */
    public function deleteByDictType($dictType)
    {
        return $this->where('dict_type', $dictType)->delete();
    }
}